import { IDepartment, IDirectory, IFileInfo, IGroup, ITarget } from '@/ts/core'
import { MenuItemType, OperateMenuType } from '@/typings/globelType'
import { command, schema } from '@/ts/base'
import OrgCtrl from '../../../ts/controller'

/** 创建团队菜单 */
const createMenu = (target: ITarget,children: MenuItemType[]) => {
  return {
    key: target.directory.key,
    item: target.directory,
    label: target.name,
    itemType: target.directory.typeName,
    menus: loadFileMenus(target.directory, 2),
    tag: [target.typeName],
    icon: '',
    remark: target.remark,
    children: children,
    beforeLoad: async () => {
      await target.loadContent()
    }
  }
}
/** 编译部门树 */
const buildDepartmentTree = async (
  departments: IDepartment[]
): Promise<MenuItemType[]> => {
  const departmentPromises = departments.map(async item => {
    await item.loadMembers()
    return createMenu(item, [
      ...(await buildDirectoryTree(item.directory.children)),
      ...(await buildDepartmentTree(item.children))
    ])
  })

  return Promise.all(departmentPromises)
}

/** 编译目录树 */
const buildDirectoryTree = (directorys: IDirectory[]): MenuItemType[] => {
  return directorys.map(directory => {
    return {
      key: directory.key,
      item: directory,
      label: directory.name,
      tag: [directory.typeName],
      icon: '',
      itemType: directory.id,
      menus: loadFileMenus(directory, 2),
      remark: directory.remark,
      children: buildDirectoryTree(directory.children),
      beforeLoad: async () => {
        await directory.loadContent()
      }
    }
  })
}
/** 编译组织集群树 */
const buildGroupTree = (groups: IGroup[]): MenuItemType[] => {
  return groups.map(item => createMenu(item))
}

export const getUserMenu = () => {
  return createMenu(OrgCtrl.user)
}

/** 获取组织菜单 */
export const getTeamMenu = () => {
  const children: MenuItemType[] = []
  for (const company of OrgCtrl.user.companys) {
    children.push(createMenu(company))
  }
  return children
}

/** 加载 单位/个人 菜单 */
export const loadCompanysMenu = async () => {
  let settingMenu: any = null
  await OrgCtrl.user.loadTeams()
  settingMenu = {
    key: '设置',
    label: '设置',
    itemType: 'Tab',
    children: [getUserMenu(), ...getTeamMenu()],
    icon: ''
  }
  return settingMenu
}

/** 加载部门下的信息 */
export const loadDepartmentsMenu = async (company: any) => {
  if (company.itemType === '单位') {
    const curCompany = OrgCtrl.user.companys.find(
      item => item.directory.key === company.key
    )
    const children: MenuItemType[] = []
    if (curCompany) {
      await curCompany.loadMembers()
      await curCompany.loadDepartments()
      await curCompany.loadGroups()
      for (const dept of curCompany.departments) {
        children.push(createMenu(dept))
      }
      return {
        key: curCompany.directory.key,
        item: curCompany.directory,
        label: curCompany.name,
        itemType: curCompany.directory.typeName,
        menus: loadFileMenus(curCompany.directory, 2),
        tag: [curCompany.typeName],
        icon: '',
        remark: curCompany.remark,
        children: children,
        beforeLoad: async () => {
          await curCompany.loadContent()
        }
      }
    }
    return children
  } else {
    const curCompany = OrgCtrl.user.companys.find(
      item => item.directory.key === company.companyKey
    )
    const curDept = curCompany?.departments.find(
      i => i.directory.key === company.key
    )
    await curDept?.loadMembers()
    return {
      key: curDept?.directory.key,
      item: curDept?.directory,
      label: curDept?.name,
      itemType: curDept?.directory.typeName,
      menus: loadFileMenus(curDept!.directory, 2),
      tag: [curDept?.typeName],
      icon: '',
      remark: curDept?.remark,
      children: curDept?.members,
      beforeLoad: async () => {
        await curDept?.loadContent()
      }
    }
  }
}

/** 加载文件菜单 */
export const loadFileMenus = (
  file: IFileInfo<schema.XEntity>,
  mode: number = 0
) => {
  return file
    .operates(mode)
    .sort((a, b) => a.sort - b.sort)
    .map(o => {
      return {
        key: o.cmd,
        label: o.label,
        icon: '',
        beforeLoad: async () => {
          if (o.cmd === 'open') {
            await file.loadContent()
          }
          command.emitter('config', o.cmd, file)
          return true
        },
        children: o.menus
          ?.sort((a, b) => a.sort - b.sort)
          .map(s => {
            return {
              key: s.cmd,
              label: s.label,
              icon: '',
              beforeLoad: async () => {
                if (s.cmd === 'open') {
                  await file.loadContent()
                }
                command.emitter('config', s.cmd, file)
                return true
              }
            }
          })
      } as OperateMenuType
    })
}
